package com.wave.wavesystem.serve.controller;

import cn.hutool.core.date.DateUtil;
import com.wave.common.constant.TimeFormatConstant;
import com.wave.common.enums.ErrorCode;
import com.wave.common.model.Result;
import com.wave.common.util.Func;
import com.wave.wavesystem.serve.constant.RedisConstant;
import com.wave.wavesystem.serve.pojo.entity.CurrentUser;
import com.wave.wavesystem.serve.service.IUserSignService;
import com.wave.wavesystem.serve.util.CurrentUserUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@RestController
@RequestMapping("/userSign")
@RequiredArgsConstructor
@Tag(name = "用户签到接口-UserSignController")
public class UserSignController {

    private final IUserSignService service;

    private final StringRedisTemplate stringRedisTemplate;

    @PostMapping("/sign")
    @Operation(summary = "签到接口")
    public Result<?> sign() {
        CurrentUser currentUser = CurrentUserUtil.getCurrentUser();
        String yyyyMM = LocalDateTime.now().format(DateTimeFormatter.ofPattern(TimeFormatConstant.YYYY_MM));
        int dayNumber = DateUtil.dayOfMonth(new Date());
        String signKey = RedisConstant.USER_SING(yyyyMM, String.valueOf(currentUser.getId()));
        Boolean bit = stringRedisTemplate.opsForValue().getBit(signKey, dayNumber - 1);
        if (Func.isNotEmpty(bit) && Boolean.TRUE.equals(bit)) {
            return Result.fail(ErrorCode.FAIL, "今天已经签到过了，明天来吧");
        }
        boolean bool = service.sign(currentUser);
        return Result.status(bool);
    }

    @PostMapping("/querySigned")
    @Operation(summary = "查询是否签到")
    public Result<?> querySigned() {
        CurrentUser currentUser = CurrentUserUtil.getCurrentUser();
        String yyyyMM = LocalDateTime.now().format(DateTimeFormatter.ofPattern(TimeFormatConstant.YYYY_MM));
        int dayNumber = DateUtil.dayOfMonth(new Date());
        String signKey = RedisConstant.USER_SING(yyyyMM, String.valueOf(currentUser.getId()));
        Boolean bit = stringRedisTemplate.opsForValue().getBit(signKey, dayNumber - 1);
        assert bit != null;
        return Result.success(bit);
    }

}
